import { useState, useEffect } from 'react';
import { cn, getImageUrl } from '@/lib/utils';
import { useActiveBanners } from '@/hooks/useBanners';
import { Banner as BannerType } from '@/types';

// 默认轮播图数据（作为后备）
const defaultSlides: BannerType[] = [
  {
    id: 1,
    title: '专业环境工程咨询',
    subtitle: '提供全方位的环境解决方案与技术支持',
    image_url: 'https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=environmental+engineering+consultants+working+on+water+treatment+plant%2C+professional+photography%2C+high+quality&sign=0e3e0ac5fc11d8ed723b2f1d0ab43fe2',
    description: '我们拥有专业的环境工程团队，为企业提供环境影响评价、污染治理等服务',
    is_active: true,
    sort_order: 1,
    created_at: new Date().toISOString()
  },
  {
    id: 2,
    title: '生态环境保护技术',
    subtitle: '创新技术应用，推动绿色可持续发展',
    image_url: 'https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=environmental+scientists+conducting+water+quality+tests+in+lab%2C+professional+photography%2C+high+quality&sign=486193060895c1904757399ddabae417',
    description: '致力于环保技术研发，推动绿色发展，创造可持续的美好未来',
    is_active: true,
    sort_order: 2,
    created_at: new Date().toISOString()
  }
];

export default function Banner() {
  const [currentSlide, setCurrentSlide] = useState(0);
  const [isTransitioning, setIsTransitioning] = useState(false);

  // 获取轮播图数据
  const { data: banners, isLoading, error } = useActiveBanners();

  // 使用API数据或默认数据
  const slides = banners && banners.length > 0 ? banners : defaultSlides;

  // Auto advance slides
  useEffect(() => {
    if (slides.length <= 1) return; // 如果只有一张图片，不自动切换

    const interval = setInterval(() => {
      nextSlide();
    }, 5000);

    return () => clearInterval(interval);
  }, [currentSlide, slides.length]);

  const nextSlide = () => {
    setIsTransitioning(true);
    setTimeout(() => {
      setCurrentSlide((prev) => (prev + 1) % slides.length);
      setIsTransitioning(false);
    }, 500);
  };

  const prevSlide = () => {
    setIsTransitioning(true);
    setTimeout(() => {
      setCurrentSlide((prev) => (prev - 1 + slides.length) % slides.length);
      setIsTransitioning(false);
    }, 500);
  };

  // 加载状态
  if (isLoading) {
    return (
      <div className="relative h-[500px] bg-gray-200 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载轮播图...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="relative h-[500px] overflow-hidden">
      {slides.map((slide, index) => (
        <div
          key={slide.id}
          className={cn(
            'absolute inset-0 transition-opacity duration-1000 ease-in-out',
            index === currentSlide ? 'opacity-100 z-10' : 'opacity-0 z-0'
          )}
        >
          <div className="absolute inset-0 bg-black/40 z-10"></div>
          <img
            src={getImageUrl(slide.image_url)}
            alt={slide.title}
            className="w-full h-full object-cover"
            onError={(e) => {
              // 图片加载失败时显示占位图
              const target = e.target as HTMLImageElement;
              target.src = getImageUrl(null);
            }}
          />
          <div className="absolute inset-0 z-20 flex items-center">
            <div className="container mx-auto px-4">
              <div className="max-w-2xl text-white">
                <h1 className="text-4xl md:text-5xl font-bold mb-4 transform transition-transform duration-700 translate-y-0">
                  {slide.title}
                </h1>
                <p className="text-xl md:text-2xl mb-8 opacity-90">
                  {slide.subtitle || slide.description}
                </p>
                {slide.link_url ? (
                  <a
                    href={slide.link_url}
                    className="inline-block bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-8 rounded-lg transition-colors transform hover:scale-105"
                  >
                    了解更多
                  </a>
                ) : (
                  <button
                    type="button"
                    className="bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-8 rounded-lg transition-colors transform hover:scale-105"
                  >
                    了解更多
                  </button>
                )}
              </div>
            </div>
          </div>
        </div>
      ))}

      {/* Navigation buttons - 只在有多张图片时显示 */}
      {slides.length > 1 && (
        <>
          <button
            type="button"
            onClick={prevSlide}
            className="absolute left-4 top-1/2 transform -translate-y-1/2 z-30 bg-white/30 hover:bg-white/50 text-white w-10 h-10 rounded-full flex items-center justify-center backdrop-blur-sm transition-colors"
            aria-label="Previous slide"
          >
            <i className="fa-solid fa-chevron-left"></i>
          </button>
          <button
            type="button"
            onClick={nextSlide}
            className="absolute right-4 top-1/2 transform -translate-y-1/2 z-30 bg-white/30 hover:bg-white/50 text-white w-10 h-10 rounded-full flex items-center justify-center backdrop-blur-sm transition-colors"
            aria-label="Next slide"
          >
            <i className="fa-solid fa-chevron-right"></i>
          </button>

          {/* Indicators */}
          <div className="absolute bottom-6 left-1/2 transform -translate-x-1/2 z-30 flex space-x-2">
            {slides.map((_, index) => (
              <button
                type="button"
                key={index}
                onClick={() => {
                  setIsTransitioning(true);
                  setTimeout(() => {
                    setCurrentSlide(index);
                    setIsTransitioning(false);
                  }, 500);
                }}
                className={cn(
                  "w-3 h-3 rounded-full transition-all duration-300",
                  index === currentSlide
                    ? "bg-white w-8"
                    : "bg-white/50 hover:bg-white/80"
                )}
                aria-label={`Go to slide ${index + 1}`}
              />
            ))}
          </div>
        </>
      )}
    </div>
  );
}